#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>


typedef struct node {
    int val;
    struct node *next;
} Node, *pNode;

pNode create_list();

bool insert_Node(pNode node, int pos, int val);

bool delete_Node(pNode node, int post, int *val);

void sort_list(pNode node);

void show_list(pNode node);

int len_list(pNode node);

bool is_empty_list(pNode node);


int main(){
    pNode p = create_list();
   // insert_Node(p,2,100);
    //show_list(p);
    int temp =0;
    delete_Node(p,2,&temp);
    show_list(p);
}


pNode create_list() {

    int len = 0;
    printf("please input the length of list: ");
    scanf("%d", &len);

    pNode pHead = (pNode) malloc(sizeof(Node));
    if (NULL == pHead) {
        printf("init the list fail");
        exit(-1);
    }
    pNode pTail = pHead;
    pTail->next = NULL;
    for (int i = 0; i < len; i++) {
        pNode pNew = (pNode) malloc(sizeof(node));
        if (NULL == pNew) {
            printf("init the list fail");
            exit(-1);
        }
        printf("please input the %d  node value :", i + 1);
        scanf("%d", &pNew->val);
        pNew->next = NULL;
        pTail->next = pNew;
        pTail = pNew;

    }
    return pHead;
}


bool is_empty_list(pNode node) {
    return NULL != node && NULL == node->next;
}


void show_list(pNode node) {
    pNode p = node->next;

    while (p) {
        printf("%d ", p->val);
        p = p->next;
    }
}

int len_list(pNode node) {
    int len = 0;

    pNode p = node->next;

    while (p) {
        len++;
        p = p->next;
    }
    return len;

}


bool insert_Node(pNode node, int pos, int val) {

    if (NULL == node || NULL == node->next) {
        return false;
    }

    int len = len_list(node);
    int i = 0;
    pNode p = node;

    while (NULL != p && i < pos - 1) {
        p = p->next;
        i++;
    }
    if (i > pos - 1 || NULL == p) {
        return false;
    }
    pNode pNew = (pNode) malloc(sizeof(Node));
    if (NULL == pNew) {
        exit(-1);
    }
    pNew->val = val;
    pNew->next = p->next;
    p->next = pNew;

    return true;
}

bool delete_Node(pNode node, int pos, int *val) {
    if (NULL == node || NULL == node->next) {
        return false;
    }

    pNode p = node;
    int i = 0;

    while (NULL != p->next && i < pos - 1) {
        p = p->next;
        i++;
    }


    if (i > pos - 1 || NULL == p->next) {
        return false;
    }
    pNode q = p->next;
    *val = q->val;
    p->next = q->next;
    free(q);
    q = NULL;
    return true;

}



























